<?php
/**
 * socket 链接库
 * @author jerry
 *
 */
class Socket
{
	var $socket;
	
	/**
	 * 创建socket链接
	 * @return unknown_type
	 */
	function init($ip,$port)
	{
		$address = gethostbyname($ip );
		
		if (($this->socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP))< 0 )
		{
			trigger_error("Couldn't create socket: " . socket_strerror(socket_last_error()) . "\n");
		}	
		
		$result = socket_connect($this->socket,$address,$port );
	}
	
	/**
	 * 发送消息体
	 * @param $msg
	 * @return unknown_type
	 */
	 function sendMsg($msg,$return = true,$pkg_len_format="N")
	 {
		socket_write($this->socket,$msg, strlen($msg) );
		
		if($return)
		{
			$buf       = socket_read($this->socket,4096);
		
			$pkg_arr   = @unpack($pkg_len_format . 'pkg_len',$buf);
	
			$proto_len = $pkg_arr["pkg_len"];
	
			while ($proto_len!=strlen($buf) )
			{
				$buf .=	socket_read($this->socket,4096);
			}	
			
			return $buf;
		}
	}
	
	function close()
	{
		if ($this->socket)
		{
			socket_close($this->socket);
		}
	}
}